package io.bdmc.modules.sys.service.impl;

import io.bdmc.modules.sys.entity.SysUserToken;
import io.bdmc.modules.sys.service.SysUserTokenService;
import io.bdmc.common.utils.R;
import io.bdmc.modules.sys.oauth2.TokenGenerator;
import org.springframework.stereotype.Service;
import io.bdmc.modules.sys.dao.SysUserTokenMapper;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


@Service("sysUserTokenService")
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenMapper, SysUserToken> implements SysUserTokenService {

	//12小时后过期
	private final static int EXPIRE = 3600 * 12;

	@Override
	public SysUserToken queryByUserId(Long userId) {

		return getById(userId);
	}

	@Override
	public SysUserToken queryByToken(String token) {
		QueryWrapper<SysUserToken> w1 = new QueryWrapper<>();
		w1.eq("token", token);
		return getOne(w1);
	}



	@Override
	public R createToken(long userId) {
		//生成一个token
		String token = TokenGenerator.generateValue();

		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		SysUserToken tokenEntity = queryByUserId(userId);
		if(tokenEntity == null){
			tokenEntity = new SysUserToken();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//保存token
			save(tokenEntity);
		}else{
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//更新token
			//update(tokenEntity);
			updateById(tokenEntity);
		}

		R r = R.ok().put("token", token).put("expire", EXPIRE);

		return r;
	}
}
